package com.renwei.yunlong.activity.contacts;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.LocationBean;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.view.RoundView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.PermissionUtil;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * 联勤动态
 */
public class ContactDynamicActivity extends BaseActivity implements SensorEventListener, RationaleListener, PermissionListener {

    @Bind(R.id.bmapView)
    MapView mMapView;
    @Bind(R.id.rv_head)
    RoundView rvHead;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_decs)
    TextView tvDecs;
    @Bind(R.id.tv_work_num)
    TextView tvWorkNum;
    @Bind(R.id.tv_total_worknum)
    TextView tvTotalWorknum;
    @Bind(R.id.tv_grade)
    TextView tvGrade;
    @Bind(R.id.ll_user_info)
    LinearLayout llUserInfo;
    public MyLocationListenner myListener = new MyLocationListenner();
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.iv_loca)
    ImageView ivLoca;
    @Bind(R.id.iv_clean)
    ImageView ivClean;
    private SensorManager mSensorManager;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;

    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private int mCurrentDirection = 0;
    private Double lastX = 0.0;

    private MyLocationData locData;
    boolean isFirstLoc = true; // 是否首次定位
    boolean isClean = false; // 是否清屏
    private LatLng llMe;
    private List<LocationBean.RowsBean> mList;
    private List<Marker> markers;
    private Marker meMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_dynamic);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.black_top), 0);
        initView();
        initData();
    }

    private void initView() {
        //初始化pop
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        // 隐藏 比例尺和加减号
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        PermissionUtil.checkSinglePermission(this, this, this, Permission.LOCATION);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        // 覆盖物marker 点击事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (markers == null) {
                    return true;
                }
                for (int i = 0; i < markers.size(); i++) {
                    if (markers.get(i) == marker) {
                        LatLng ll = marker.getPosition();
                        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popu_location_layout, null);
                        initInfoView(contentView, mList.get(i));
                        InfoWindow mInfoWindow = new InfoWindow(contentView, ll, -150);
                        mBaiduMap.showInfoWindow(mInfoWindow);

                        // 回到当前位置
                        MapStatus mMapStatus = new MapStatus.Builder()
                                .target(ll)
                                .zoom(mBaiduMap.getMapStatus().zoom)
                                .build();
                        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                        //改变地图状态
                        mBaiduMap.animateMapStatus(mMapStatusUpdate);
                    }
                }
                return true;
            }
        });
        ivLoca.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 回到当前位置
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(new LatLng(mCurrentLat, mCurrentLon))
                        .zoom(16)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);
            }
        });
        ivClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清屏 or 显示
                clearLayout();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void clearLayout() {
        if (isClean) {
            isClean = false;
            llUserInfo.setVisibility(View.VISIBLE);
            ivClean.setImageResource(R.mipmap.icon_map_clean);
        } else {
            isClean = true;
            llUserInfo.setVisibility(View.GONE);
            ivClean.setImageResource(R.mipmap.icon_map_reset);
            mBaiduMap.hideInfoWindow();
        }
    }

    private void initInfoView(View contentView, final LocationBean.RowsBean bean) {
        RoundView infoRvHead = contentView.findViewById(R.id.rv_head);
        TextView infoTvName = contentView.findViewById(R.id.tv_name);
        TextView infoTvDecs = contentView.findViewById(R.id.tv_decs);
        TextView infoTvWorkNum = contentView.findViewById(R.id.tv_work_num);
        TextView infoTvTotalWorknum = contentView.findViewById(R.id.tv_total_worknum);
        TextView infoTvGrade = contentView.findViewById(R.id.tv_grade);
        contentView.findViewById(R.id.iv_call).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + bean.getMobilePhone()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });
        contentView.findViewById(R.id.iv_msg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("url", "1".equals(companyType) ? Api.$().OWNER_FILE_URL + bean.getAvatar() : Api.$().SERVICE_FILE_URL + bean.getAvatar());
                RongIM.getInstance().startConversation(mContext, Conversation.ConversationType.PRIVATE,
                        bean.getEmployeeId(), bean.getName(), bundle);
            }
        });

        Glide.with(mContext).load("1".equals(companyType) ? Api.$().OWNER_FILE_URL + bean.getAvatar() : Api.$().SERVICE_FILE_URL + bean.getAvatar())
                .error(R.mipmap.icon_header_default).into(infoRvHead);
        infoTvName.setText(bean.getName());
        infoTvDecs.setText(bean.getDepartmentName());
        infoTvWorkNum.setText(bean.getWorkNum() + "");
        infoTvTotalWorknum.setText(bean.getTotalWorkNum() + "");
        infoTvGrade.setText(bean.getServerGrade());

    }

    private void initData() {
        HttpPresenter hp = new HttpPresenter(this);
        if ("1".equals(companyType)) {
            hp.setUrl(Api.$().OWNER_LOCATION);
            hp.putParam("jsonBean", ownerBean.getRows().getOwnerCode());
        } else if ("2".equals(companyType)) {
//            hp.setUrl(Api.$().SERVICE_LOCATION);
            hp.setUrl(Api.$().SERVICE_LOCATION);
            hp.putParam("jsonBean", serviceLoginBean.getRows().getServiceProviderCode());
        }
        hp.setshowDialogcontent("正在加载");
        hp.setCallBack(new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                LocationBean bean = new Gson().fromJson(result, LocationBean.class);
                if (bean.getMessage().getCode() == 200) {
                    setData(bean.getRows());
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
        hp.post();
    }


    /**
     * 设置 数据
     *
     * @param beans
     */
    private void setData(List<LocationBean.RowsBean> beans) {
        String employeeId = "";
        if ("1".equals(companyType)) {
            employeeId = ownerBean.getRows().getEmployeeId();
        } else if ("2".equals(companyType)) {
            employeeId = serviceLoginBean.getRows().getEmployeeId();
        }

        // 存储Marker 集合
        markers = new ArrayList<>();
        mList = new ArrayList<>();
        for (int i = 0; i < beans.size(); i++) {
            LocationBean.RowsBean bean = beans.get(i);
            if (beans.get(i).getEmployeeId().equals(employeeId)) {
                // 个人信息
                Glide.with(mContext).load("1".equals(companyType) ? Api.$().OWNER_FILE_URL + bean.getAvatar() : Api.$().SERVICE_FILE_URL + bean.getAvatar())
                        .error(R.mipmap.icon_header_default).into(rvHead);
                tvName.setText(bean.getName());
                tvDecs.setText(bean.getDepartmentName());
                tvWorkNum.setText(bean.getWorkNum() + "");
                tvTotalWorknum.setText(bean.getTotalWorkNum() + "");
                tvGrade.setText(bean.getServerGrade());
            } else {
                LatLng llOhter = new LatLng(Double.valueOf(bean.getLatitude()), Double.valueOf(bean.getLongitude()));
                String url = "1".equals(companyType) ? Api.$().OWNER_FILE_URL + bean.getAvatar() : Api.$().SERVICE_FILE_URL + bean.getAvatar();
                addMapOver(false, llOhter, R.mipmap.icon_map_loc_other, url, bean);
            }
        }


    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(ContactDynamicActivity.this, rationale).show();
    }

    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        switch (requestCode) {
            case PermissionUtil.LOCATION:
                initData();
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(ContactDynamicActivity.this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(ContactDynamicActivity.this, PermissionUtil.SETTING_CODE).show();
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map icon_work_watch 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            if (llMe == null) {
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                String url = "1".equals(companyType) ? Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar()
                        : Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar();
                addMapOver(false, llMe, R.mipmap.icon_map_loc_me, url, null);
            }else {
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                if (meMarker!=null) {
                    meMarker.setPosition(llMe);
                }
            }
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.0f);
                // 设置地图参数
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    private void addMapOver(final boolean isFirst, final LatLng latLng, final int imgRes, final String url, final LocationBean.RowsBean bean) {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_map_icon, null);
        RelativeLayout rlMap = view.findViewById(R.id.rl_map);
        rlMap.setBackgroundResource(imgRes);
        final RoundView rvMap = view.findViewById(R.id.rv_head);
        Glide.with(mContext).load(url)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        rvMap.setImageResource(R.mipmap.icon_header_default);
                        BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                        MarkerOptions ooMe = new MarkerOptions().position(latLng).icon(locMe)
                                .zIndex(1).draggable(true);
                        Marker marker = (Marker) mBaiduMap.addOverlay(ooMe);
                        if (bean!=null){
                            mList.add(bean);
                            markers.add(marker);
                        }else{
                            meMarker = marker;
                        }
                        marker.setToTop();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isFirst) {
                                    BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                                    MarkerOptions ooMe = new MarkerOptions().position(latLng).icon(locMe)
                                            .zIndex(1).draggable(true);

                                    Marker marker = (Marker) mBaiduMap.addOverlay(ooMe);
                                    if (bean!=null){
                                        mList.add(bean);
                                        markers.add(marker);
                                    }else{
                                        meMarker = marker;
                                    }
                                    marker.setToTop();
                                } else {
                                    addMapOver(true, latLng, imgRes, url, bean);
                                }
                            }
                        }, 500);
                        return false;
                    }
                }).into(rvMap);
    }

    /**
     * 把View转换成Bitmap类型
     *
     * @return
     * @paramaddViewContent要转换的View
     */
    public Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());


        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }

    public static void OpenActivity(Context context) {
        Intent intent = new Intent(context, ContactDynamicActivity.class);
        context.startActivity(intent);
    }
}
